package com.eascs.admin.o2o.loan.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.controller.ContractRestController;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.loan.entity.BCRecommendationEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.BCRecommendationService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.common.doc.word.WordBuilder;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.crm.nsEditDetail.entity.O2oMainShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.IMainShopInfoService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.workflow.common.vo.ModelResult;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;



/**
 * @Description: 推荐函打印
 */
@RestController
public class RecommendationRestController extends BaseRestController {
	
	private final static String MONEY_UNIT="万元";
	private final static String MONTH_UNIT="个月";
	private final static String YEAR_UNIT="年";

	@Autowired
	private BCRecommendationService bcRecommendationService;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	@Autowired
	private O2oLoanUserService loanService;
	
	@Reference
	IMainShopInfoService mainShopInfoService;
	@Autowired
	private O2oZxServiceImpl  o2oZxServiceImpl;
	
	@Autowired
	private O2oPubDdItemService o2oPubDdItemService;
	
	/**
	 * @Title: 推荐函打印下载
	 */
	@RequestMapping(value = "/downloadRecommendationPDF", method = RequestMethod.GET)
	public void downloadRecommendationPDF(HttpServletResponse httpServletResponse, HttpServletRequest request,String loanapplyNo) { 
		OutputStream os = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			String templateUrl="/pdfTemplate/recommendation.pdf";//合同文件模板相对路径
			URL base=ContractRestController.class.getResource(templateUrl);
			String templateFile = base.getFile();//合同文件模板绝对路径
			PdfReader reader = new PdfReader(templateFile); // 模版文件目录  
			// PdfStamper ps = new PdfStamper(reader, new FileOutputStream("f:/fillTemplate.pdf")); // 生成的输出流  
			PdfStamper ps = new PdfStamper(reader, bos);  
			AcroFields acroFields = ps.getAcroFields();  
			fillData(acroFields,loanapplyNo);
			ps.setFormFlattening(true);
			ps.close();  
			reader.close();  
			
			String outfile = "";
			outfile = "中行推荐函(201512版).pdf";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/pdf");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			os.write(bos.toByteArray());
			os.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			IoUtil.close(os);
		}
	}  
	private Map<String, Object> fillZLData(String loanapplyNo) { //中行
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUserEntity = loanService.findById(loanapplyEntity.getLoanId(), loanapplyNo);
		
		BigDecimal loanMoney = new BigDecimal("10000");
		BigDecimal zero = new BigDecimal("0");
		BigDecimal loanAmount =loanapplyEntity.getEaMount() == null ? zero : loanapplyEntity.getLoanaMount();
		BigDecimal eaMount = loanapplyEntity.getEaMount() == null ? zero : loanapplyEntity.getEaMount();
		eaMount = eaMount.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP);
		loanAmount = loanAmount.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP);
		
		data.put("customerName", loanUserEntity.getUserFullName());  
		data.put("IDcardNo", loanUserEntity.getDocumentNo());  
		data.put("eaMoney", eaMount.toString() + MONEY_UNIT);  
		data.put("loanTerm", loanapplyEntity.getLoanTerm() + MONTH_UNIT);
		data.put("loanAmount", loanAmount.toString() + MONEY_UNIT); 
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(loanUserEntity.getZxNo());// 征信
		//近一年向怡亚通采购额  转化成万元
		if(o2oZxEntity.getPurchaseAmount()!=null){
			data.put("yearAmount", o2oZxEntity.getPurchaseAmount().divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP).toString()+MONEY_UNIT);  
		}
		
		//从业年限
		O2oMainShopInfoEntity info = mainShopInfoService.getByLoanNo(loanapplyNo);
		Date qssj = info.getBusinesshours();//营业起始时间
		Date enddate = new Date();
		int bewYear = 0;
		int qssjyear = DateUtils.getYear(qssj);
		int endyear = DateUtils.getYear(new Date());
		int qssjmoth = DateUtils.getMonth(qssj);
		int endmoth = DateUtils.getMonth(enddate);
		int qssjday = DateUtils.getDay(qssj);
		int endday = DateUtils.getDay(enddate);
		bewYear = endyear - qssjyear;
		int bewday = endday - qssjday;
		if(endmoth - qssjmoth >0){
			bewYear = bewYear +1;
		}else if(endmoth - qssjmoth == 0){
			if(bewday >0){
				bewYear = bewYear +1;
			}
		}
		data.put("bewYear", bewYear+YEAR_UNIT); 
		
		//经营行业分类
		data.put("operateIndustry",o2oPubDdItemService.findPubdditemO2ONameByCode("vocation", info.getVocation()) ); 
		/*String bankName = o2oPubDdItemService.findPubdditemNameByCode("vocation", info.getVocation());
		PubDditem p = pubDditemService.queryPubDditemO2o("l6rkja9fqcb0a",shop.getVocation());// 职业
*/		return data;
	}
	
	@RequestMapping(value = "/downloadRecommendation_word", method = RequestMethod.GET)
	public void downloadSPDBGZContract_word(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		// 最后需要生产的模板文件
		String classPathFiles = "/wordTemplate/zhtjh201711.xml";
		Map<String, Object> data = fillZLData(loanapplyNo);
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = "中行调查表推荐函201711版.doc";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/doc");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			WordBuilder.buildDocFromXml(os, data, classPathFiles);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
	

	/**
	 * @Title: fillData
	 * @Description: 填充pdf数据
	 */
	private void fillData(AcroFields s,String loanapplyNo) throws Exception{
		BCRecommendationEntity bcRecommendation=new BCRecommendationEntity();
		ModelResult<BCRecommendationEntity> modelResult=bcRecommendationService.queryBCRecommendationByLoanNo(loanapplyNo);
		if (modelResult.getModel() != null) {
			//NumberFormat nf = new DecimalFormat(",###");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
			bcRecommendation=modelResult.getModel();
			s.setField("loanProduct", bcRecommendation.getLoanProduct());
			s.setField("customerName", bcRecommendation.getCustomerName());  
			s.setField("IDcardNo", bcRecommendation.getIDcardNo());  
			s.setField("loanMoney", bcRecommendation.getLoanMoney().toString() + MONEY_UNIT);  
			s.setField("loanTerm", bcRecommendation.getLoanTerm() + MONTH_UNIT);  
			s.setField("loanUse", bcRecommendation.getLoanUse());  
			s.setField("loanCount", bcRecommendation.getLoanCount().toString());  
			s.setField("lastOrderMoney", bcRecommendation.getLastOrderMoney().toString() + MONEY_UNIT);  
			s.setField("annualIncome", bcRecommendation.getAnnualIncome().toString() + MONEY_UNIT);  
			s.setField("eascsAvgOrderMoney", bcRecommendation.getEascsAvgOrderMoney().toString() + MONEY_UNIT);  
			s.setField("avgOrderMoney", bcRecommendation.getAvgOrderMoney().toString() + MONEY_UNIT);  
			s.setField("operateIndustry", bcRecommendation.getOperateIndustry());  
			s.setField("eascsCooperationTerm", bcRecommendation.getEascsCooperationTerm() + YEAR_UNIT);  
			s.setField("suggestMoney", bcRecommendation.getSuggestMoney().toString() + MONEY_UNIT);  
			s.setField("suggestTerm", bcRecommendation.getSuggestTerm() + MONTH_UNIT);  
			s.setField("approveMoney", bcRecommendation.getApproveMoney().toString() + MONEY_UNIT);  
			s.setField("approveTerm", bcRecommendation.getApproveTerm() + MONTH_UNIT);  
			s.setField("remarksComments", bcRecommendation.getRemarksComments());
			s.setField("review_time", sdf.format(bcRecommendation.getReviewTime()));  
			s.setField("approveTime", sdf.format(bcRecommendation.getApproveTime()));  
		}
	}

	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	@SuppressWarnings("unused")
	private BigDecimal formatComma2BigDecimal(Object obj) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");

		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");

		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(2, BigDecimal.ROUND_UP);

		return decimal;

	}

	@SuppressWarnings("unused")
	private static String[] buildMountNumber(Number number) {
		DecimalFormat df = new DecimalFormat("0.00");
		String mountStr = df.format(number);
		mountStr = "￥" + mountStr.replace(".", "");
		String[] numberArray = new String[10];
		int j = 0;
		for (int i = 0; i < numberArray.length; i++) {
			numberArray[i] = "";
			if (mountStr.length() >= 10 - i) {
				numberArray[i] = mountStr.substring(j, j + 1);
				j++;
			}
		}
		return numberArray;
	}
}
